package com.yao2san.sim.storage.client.core.downloader;

import com.yao2san.sim.storage.client.config.MinioProperties;
import com.yao2san.sim.storage.client.core.enums.StorageType;
import com.yao2san.sim.storage.client.util.StorageUtil;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MinioDownloader extends AbstractDownloader {

    private final MinioProperties minioProperties;
    private final MinioClient client;

    public MinioDownloader(MinioClient client, MinioProperties minioProperties) {
        this.client = client;
        this.minioProperties = minioProperties;
    }

    @Override
    public void download(String object, OutputStream out) {
        StorageUtil.checkObjectName(object);
        try (GetObjectResponse response = client.getObject(
                GetObjectArgs.builder()
                        .object(object)
                        .bucket(minioProperties.getBucket())
                        .build())) {
            IOUtils.copy(response, out);
        } catch (ErrorResponseException | NoSuchAlgorithmException |
                 InsufficientDataException | InternalException |
                 InvalidKeyException | InvalidResponseException |
                 IOException | ServerException | XmlParserException e) {
            log.error("file download error", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public String url(String object) {
        return url(object, false);
    }

    @Override
    public String url(String object, boolean preSigned) {
        if (preSigned) {
            try {
                return client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .object(object)
                        .bucket(minioProperties.getBucket())
                        .method(Method.GET)
                        .expiry(30, TimeUnit.MINUTES)
                        .build());
            } catch (ErrorResponseException | NoSuchAlgorithmException |
                     InsufficientDataException | InternalException |
                     InvalidKeyException | InvalidResponseException |
                     IOException | ServerException | XmlParserException e) {
                log.error("file download error", e);
                throw new RuntimeException(e);
            }
        } else {
            return minioProperties.getBucket() + "." + minioProperties.getEndpoint() + "/" + object;
        }
    }

    @Override
    public String getName() {
        return StorageType.MINIO.name();
    }
}
